var uploadMap;
var isIE=false;

function submitForms(groupID,instanceID)
{
	var fileForm = document.getElementById("fileform_" + groupID);
	
	 fileForm.action = uploadHandler + "/" + instanceID;
		  
	 fileForm.target = "upload_frame_" + instanceID;
	
	 fileForm.submit();
}

function removeProgressBar(groupID,instanceID)
{
	var progressBarHolder = document.getElementById("progressBarHolder_" + groupID);	
	
	var progressBarWrapper = document.getElementById("progressBarDataWrapperElement_" + instanceID);
	progressBarHolder.removeChild(progressBarWrapper);	
}

function addRemoveButton(fileName,fileSessionID,groupID,instanceID)
{
	var removeButtonHolder = document.getElementById("RemoveButton_" + groupID);
	
	var currentStyle = removeButtonHolder.style.display;
	removeButtonHolder.style.display="block";
	
	var fileNameElement = document.createElement('span');
	fileNameElement.id = "fileNameElement_" + instanceID; 
	fileNameElement.className="fileNameElementCSS";
	
	if(currentStyle=="block")
		{
			var addCommaElement = document.createElement('span');
			addCommaElement.id = "addCommaElement_" + instanceID; 
			addCommaElement.innerHTML = ",";
			addCommaElement.className="addCommaElementCSS";
			
			removeButtonHolder.appendChild(addCommaElement);
		}
	
	fileNameElement.innerHTML=fileName;
	
	var progressBarRemoveLinkElement = document.createElement('a');
	progressBarRemoveLinkElement.id = "progressBarRemoveLink_" + instanceID; 
	progressBarRemoveLinkElement.className="progressBarRemoveLinkCSS";
	progressBarRemoveLinkElement.href="javascript:deleteFileAsynch('" + instanceID + "','" + groupID + "','" + fileName + "','" + fileSessionID + "');" 
	//progressBarRemoveLinkElement.onclick = "deleteFileAsynch(" + instanceID + "," + groupID + "," + fileName + "," + fileSessionID + ");";
	
	progressBarRemoveLinkElement.innerHTML="x";
	
	removeButtonHolder.appendChild(fileNameElement);
	removeButtonHolder.appendChild(progressBarRemoveLinkElement);
}

function createProgressBar(groupID,instanceID,fileName){
	
	var progressBarHolder = document.getElementById("progressBarHolder_" + groupID);	
	
	
	var progressBarDataWrapperElement = document.createElement('span');
    progressBarDataWrapperElement.className = "progressBarDataWrapperElementCSS";
    progressBarDataWrapperElement.id = "progressBarDataWrapperElement_" + instanceID;
    
	var progressBarWrapperElement = document.createElement('span');
    progressBarWrapperElement.className = "progressBarWrapperCSS";
    progressBarWrapperElement.id = "progressBarWrapper_" + instanceID;
    
    var progressBarElement = document.createElement('span');
    progressBarElement.className = "progressBarCSS";
    progressBarElement.id = "progressBar_" + instanceID;
    
    var progressBarNameElement = document.createElement('span');
    progressBarNameElement.className = "progressBarNameCSS";
    progressBarNameElement.id = "progressBarName_" + instanceID;
   
    progressBarNameElement.innerHTML = "Uploading " + fileName;
    
    
    var progressBarDataElement = document.createElement('span');
    progressBarDataElement.className = "progressBarDataCSS";
    progressBarDataElement.id = "progressBarData_" + instanceID;
    
    var progressBarCancelElement = document.createElement('span');
    progressBarCancelElement.className = "progressBarCancelElementCSS";
    progressBarCancelElement.id = "progressBarCancelElement_" + instanceID;
    
    progressBarWrapperElement.appendChild(progressBarElement);
    progressBarWrapperElement.appendChild(progressBarDataElement);
    
    var progressBarCancelLinkElement = document.createElement('a');
    progressBarCancelLinkElement.id = "progressBarCancelLink_" + instanceID; 
    progressBarCancelLinkElement.className="progressBarCancelLinkCSS";
    progressBarCancelLinkElement.href= uploadHandler + "?cancelFile=true&id=" + instanceID;
    progressBarCancelLinkElement.target="upload_frame_" + instanceID; 
    progressBarCancelLinkElement.onclick = function(){
		var id = this.id;
		var instanceID = id.substring(id.indexOf('_')+ 1);
		var wrapperHolderElement = document.getElementById("progressBarDataWrapperElement_" + instanceID);
		wrapperHolderElement.style.display = "none";
		//var wrapperElement = document.getElementById("progressBarWrapper_" + instanceID);
	}
	
    progressBarCancelLinkElement.innerHTML="Cancel";
    
    //progressBarWrapperElement.appendChild(progressBarCancelLinkElement);
    progressBarNameElement.appendChild(progressBarCancelLinkElement);
    
    progressBarDataWrapperElement.appendChild(progressBarNameElement);
    progressBarDataWrapperElement.appendChild(progressBarWrapperElement);    
  //  progressBarDataWrapperElement.appendChild(progressBarCancelLinkElement);
    
	progressBarHolder.appendChild(progressBarDataWrapperElement);
	 
	progressBarWrapperElement.style.display = 'block';	
	progressBarWrapperElement.style.width = progressBarMaxSize + 'px';	
	
	progressBarDataWrapperElement.style.display = 'block';	
	progressBarDataWrapperElement.style.width = (eval(progressBarMaxSize) + 10) + 'px';	
	
	progressBarDataElement.style.display = 'block';	
	progressBarDataElement.style.width = progressBarMaxSize + 'px';
	
	progressBarElement.style.display = 'block';	
	progressBarElement.style.width = "2px";  
}
  
function sendFileAsynch(groupName,target)
{
	generateFileSession(target,groupName);
}

function updateProgressBar(progressBarValue,instanceID)
{
	var progressbar = document.getElementById("progressBar_" + instanceID);
	var progressbarData = document.getElementById("progressBarData_" + instanceID);
	
	progressbarData.innerHTML = progressBarValue + "%";
//	alert("updating progress bar " + progressBarValue);
	
	progressbar.style.width = progressBarMaxSize * (progressBarValue/100) +  "px";     
	
}

function generateFileSession(target,groupName){
	
var count = uploadMap['Uploaddiv_' + groupName];
uploadMap['Uploaddiv_' + groupName] = eval(count) + 1;

var instanceID = groupName + "_" + count;

var url = target + "?id=" + instanceID + "&groupName=" + groupName + "&createFileSession=true";
    
	var req;
	
    if (window.XMLHttpRequest){ 
        req = new XMLHttpRequest();
        try{
            req.onreadystatechange = function() { handleFileSession(req); };
            req.open("GET", url, true);
        } catch (e) {
            alert(e);
        }
        req.send(null);
    }

    else if (window.ActiveXObject) { 
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { handleFileSession(req); };
            req.open("GET", url, true);
            req.send();
        }
    }
}

function deleteFileAsynch(instanceID,groupID,fileName,fileSessionID)
{

var url = uploadHandler + "?deleteFile=true&id=" + instanceID + "&groupName=" + groupID + "&fileName=" + fileName + "&fileSessionID=" + fileSessionID;
    
	var req;
	
    if (window.XMLHttpRequest){ 
        req = new XMLHttpRequest();
        try{
            req.onreadystatechange = function() { handleFileDelete(req); };
            req.open("GET", url, true);
        } catch (e) {
            alert(e);
        }
        req.send(null);
    }

    else if (window.ActiveXObject) { 
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { handleFileDelete(req); };
            req.open("GET", url, true);
            req.send();
        }
    }
}


function checkFileStatus(instanceID){
    
	var url = uploadHandler + "?id=" + instanceID;
    
	var req;
	
    if (window.XMLHttpRequest){ 
        req = new XMLHttpRequest();
        try{
            req.onreadystatechange = function() { handleFileProgress(req); };
            req.open("GET", url, true);
        } catch (e) {
            alert(e);
        }
        req.send(null);
    }

    else if (window.ActiveXObject) { 
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() { handleFileProgress(req); };
            req.open("GET", url, true);
            req.send();
        }
    }
    
    
}

function handleFileDelete(req)
{
	 if (req.readyState == 4){
	        if (req.status == 200){
	        	
	            var xml = req.responseXML;
	            var deleteNode = xml.getElementsByTagName("fileDelete")[0];
	            var result = deleteNode.getElementsByTagName("delete")[0].childNodes[0].nodeValue;
	            var instanceID = deleteNode.getElementsByTagName("instanceID")[0].childNodes[0].nodeValue;
	            var groupID = deleteNode.getElementsByTagName("groupID")[0].childNodes[0].nodeValue;
	            
	            if(result=="true"){
	            	var errorNode=xml.getElementsByTagName("error")[0];
	            	
	            	var removeButtonHolder = document.getElementById("RemoveButton_" + groupID);
	            	
	            	var progressBarRemoveLinkElement = document.getElementById("progressBarRemoveLink_" + instanceID);
	            	var progressBarFileNameElement = document.getElementById("fileNameElement_" + instanceID);
	            	var progressBarAddCommaElement = document.getElementById("addCommaElement_" + instanceID);
	            	
	            	removeButtonHolder.removeChild(progressBarRemoveLinkElement);
	            	removeButtonHolder.removeChild(progressBarFileNameElement);
	            	
	            	if(progressBarAddCommaElement)
	            		removeButtonHolder.removeChild(progressBarAddCommaElement);
	            	else
	            		removeButtonHolder.style.display="none";
	            	
	            	return;
	            }else
	            	{
	            		alert('Could not delete file on server.')
	            		return;
	            	}
	      
	        } else {
	            alert(req.statusText);
	        }
	    }
}

function handleFileProgress(req){
    if (req.readyState == 4){
        if (req.status == 200){
        	
            var xml = req.responseXML;
            if(xml.getElementsByTagName("response")[0]==null)
            {
            	var errorNode=xml.getElementsByTagName("error")[0];
            	var instanceID = errorNode.getElementsByTagName("instanceID")[0].childNodes[0].nodeValue;
            	var fileSessionID = errorNode.getElementsByTagName("fileSessionID")[0].childNodes[0].nodeValue;
            	
            	if(fileSessionID=='NULL')
            		return;
            	
            	setTimeout("checkFileStatus('" + instanceID + "');", progressFrequency);
            	return;
            }
            
            var responseNode=xml.getElementsByTagName("response")[0];
            var instanceID = responseNode.getElementsByTagName("instanceID")[0].childNodes[0].nodeValue;
            var fileName = responseNode.getElementsByTagName("fileName")[0].childNodes[0].nodeValue;
            var fileSessionID = responseNode.getElementsByTagName("fileSessionID")[0].childNodes[0].nodeValue;
            var groupID = responseNode.getElementsByTagName("groupID")[0].childNodes[0].nodeValue;
            var message = responseNode.getElementsByTagName("message")[0].childNodes[0].nodeValue;
            
            if (responseNode.getElementsByTagName("percent_complete")[0]!=null){
            	
            	setTimeout("checkFileStatus('" + instanceID + "');", progressFrequency);
              	
                var progressBarValue = responseNode.getElementsByTagName("percent_complete")[0].childNodes[0].nodeValue;
                setTimeout("updateProgressBar('" + progressBarValue + "','"+ instanceID +"');", progressFrequency);
                
                if(progressBarValue==100)
                	{
	                	var progressBarNameElement = document.getElementById("progressBarName_" + instanceID);
	            		var progressBarNameElementHTML =  progressBarNameElement.innerHTML;
	            	
                		if(progressBarNameElementHTML.indexOf('Uploading') > -1)
                		{
                			var progressBarCancelLinkElement = document.getElementById("progressBarCancelLink_" + instanceID);
            				progressBarCancelLinkElement.style.display="none";
            				progressBarNameElement.removeChild(progressBarCancelLinkElement);
            				
                			var progressBarNameElementHTML = progressBarNameElement.innerHTML;
                			progressBarNameElement.innerHTML = progressBarNameElementHTML.replace('Uploading','Saving') + " ...";
                				
                		}
                	}                
                   
            } else {
            	
            	var status = responseNode.getElementsByTagName("result")[0].childNodes[0].nodeValue;
            	if(status=='SUCCESS')
            	{
            		updateProgressBar(100,instanceID);
            		removeProgressBar(groupID,instanceID);
            		addRemoveButton(fileName,fileSessionID,groupID,instanceID);
            	}else
            	{
            		alert(message);
            		removeProgressBar(groupID,instanceID);
            	}            		
             }
        } else {
            alert(req.statusText);
        }
    }
}

function handleFileSession(req)
{
	
	    if (req.readyState == 4){
	        if (req.status == 200){	      
	        	
	            var xml = req.responseXML;
	            
	          	var fileSessionNode=xml.getElementsByTagName("filesession")[0];
	          	
	            var instanceID = fileSessionNode.getElementsByTagName("instanceID")[0].childNodes[0].nodeValue;
	            var groupID = fileSessionNode.getElementsByTagName("groupid")[0].childNodes[0].nodeValue;
	            
	            createFileForm(groupID,instanceID);	            
	        }else {
	            alert(req.statusText);
	        }
	    }
}

function createFileForm(groupID,instanceID)
{
	//var iFrameHTML = '<iframe src='' name="upload_frame_"' + instanceID + '"/>';
//	var iFrameElement = document.createElement(iFrameHTML);
	
	createFileIframe(groupID,instanceID);    
    
    var fileElement = document.getElementById('datafile_' + groupID);
    
    var filepath = fileElement.value;
    var fileName;
    
    if(filepath.indexOf('\\') > -1)
    {
    	fileName = filepath.substring((filepath.lastIndexOf('\\') + 1));
    }else
    	fileName = filepath;
    
 //   outerdiv.appendChild(formElement);
    
    
    // outerdiv.innerHTML = formHTML + progressBarHTML + iFrameHTML;       
    submitForms(groupID,instanceID);
    createProgressBar(groupID,instanceID,fileName);
	checkFileStatus(instanceID);   
}

function createFileIframe(groupID,instanceID)
{
	  var frameId = "upload_frame_" + instanceID;
     
		if(isIE)
			{
				var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" class="iFrameElementCSS"';
				
				if(window.ActiveXObject)
				{
		          	iframeHtml += ' src="' + 'javascript:false' + '"';
		        }
				iframeHtml += ' />';
				
				var bodyElement = document.body;
				
				document.body.appendChild(document.createElement(iframeHtml));
			}
		else
			{
				var IframeElement = document.createElement('iframe');
				IframeElement.className = "iFrameElementCSS";
				IframeElement.name = frameId;
				IframeElement.id = frameId;				
				IframeElement.src = "#";
				
				var uploadDiv = document.getElementById("Uploaddiv_" + groupID);
				uploadDiv.appendChild(IframeElement);
			}
	//	document.body.appendChild(document.createElement(iframeHtml));

   //   return jQuery('#' + frameId).get(0);		

	
        
    //var uploadDiv = document.getElementById("Uploaddiv_" + groupID);
    //uploadDiv.appendChild(iFrameElement);
}

function initFileUploads() {
	
	var x = document.getElementsByTagName('input');
	
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].className != 'hiddenFileElement') continue;
		
		var fileElementWidth = x[i].offsetWidth
		var parentWidth = x[i].parentNode.parentNode.offsetWidth;
		
		
		var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
		
		if(is_chrome)
			x[i].width = parentWidth + "px";
		else
			{
				x[i].size=1;
				x[i].width = (parentWidth - 90) + "px";
			}
		}	
}

function getElementsByName_iefix(tag, name) {
    
    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for(i = 0,iarr = 0; i < elem.length; i++) {
         att = elem[i].getAttribute("name");
         if(att == name) {
              arr[iarr] = elem[i];
              iarr++;
         }
    }
    return arr;
}

var ready = (function(){    

    var readyList,
        DOMContentLoaded,
        class2type = {};
        class2type["[object Boolean]"] = "boolean";
        class2type["[object Number]"] = "number";
        class2type["[object String]"] = "string";
        class2type["[object Function]"] = "function";
        class2type["[object Array]"] = "array";
        class2type["[object Date]"] = "date";
        class2type["[object RegExp]"] = "regexp";
        class2type["[object Object]"] = "object";

    var ReadyObj = {
        // Is the DOM ready to be used? Set to true once it occurs.
        isReady: false,
        // A counter to track how many items to wait for before
        // the ready event fires. See #6781
        readyWait: 1,
        // Hold (or release) the ready event
        holdReady: function( hold ) {
            if ( hold ) {
                ReadyObj.readyWait++;
            } else {
                ReadyObj.ready( true );
            }
        },
        // Handle when the DOM is ready
        ready: function( wait ) {
            // Either a released hold or an DOMready/load event and not yet ready
            if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if ( !document.body ) {
                    return setTimeout( ReadyObj.ready, 1 );
                }

                // Remember that the DOM is ready
                ReadyObj.isReady = true;
                // If a normal DOM Ready event fired, decrement, and wait if need be
                if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                    return;
                }
                // If there are functions bound, to execute
                readyList.resolveWith( document, [ ReadyObj ] );

                // Trigger any bound ready events
                //if ( ReadyObj.fn.trigger ) {
                //  ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                //}
            }
        },
        bindReady: function() {
            if ( readyList ) {
                return;
            }
            readyList = ReadyObj._Deferred();

            // Catch cases where $(document).ready() is called after the
            // browser event has already occurred.
            if ( document.readyState === "complete" ) {
                // Handle it asynchronously to allow scripts the opportunity to delay ready
                return setTimeout( ReadyObj.ready, 1 );
            }

            // Mozilla, Opera and webkit nightlies currently support this event
            if ( document.addEventListener ) {
                // Use the handy event callback
                document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                // A fallback to window.onload, that will always work
                window.addEventListener( "load", ReadyObj.ready, false );

            // If IE event model is used
            } else if ( document.attachEvent ) {
                // ensure firing before onload,
                // maybe late but safe also for iframes
                document.attachEvent( "onreadystatechange", DOMContentLoaded );

                // A fallback to window.onload, that will always work
                window.attachEvent( "onload", ReadyObj.ready );

                // If IE and not a frame
                // continually check to see if the document is ready
                var toplevel = false;

                try {
                    toplevel = window.frameElement == null;
                } catch(e) {}

                if ( document.documentElement.doScroll && toplevel ) {
                    doScrollCheck();
                }
            }
        },
        _Deferred: function() {
            var // callbacks list
                callbacks = [],
                // stored [ context , args ]
                fired,
                // to avoid firing when already doing so
                firing,
                // flag to know if the deferred has been cancelled
                cancelled,
                // the deferred itself
                deferred  = {

                    // done( f1, f2, ...)
                    done: function() {
                        if ( !cancelled ) {
                            var args = arguments,
                                i,
                                length,
                                elem,
                                type,
                                _fired;
                            if ( fired ) {
                                _fired = fired;
                                fired = 0;
                            }
                            for ( i = 0, length = args.length; i < length; i++ ) {
                                elem = args[ i ];
                                type = ReadyObj.type( elem );
                                if ( type === "array" ) {
                                    deferred.done.apply( deferred, elem );
                                } else if ( type === "function" ) {
                                    callbacks.push( elem );
                                }
                            }
                            if ( _fired ) {
                                deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                            }
                        }
                        return this;
                    },

                    // resolve with given context and args
                    resolveWith: function( context, args ) {
                        if ( !cancelled && !fired && !firing ) {
                            // make sure args are available (#8421)
                            args = args || [];
                            firing = 1;
                            try {
                                while( callbacks[ 0 ] ) {
                                    callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                }
                            }
                            finally {
                                fired = [ context, args ];
                                firing = 0;
                            }
                        }
                        return this;
                    },

                    // resolve with this as context and given arguments
                    resolve: function() {
                        deferred.resolveWith( this, arguments );
                        return this;
                    },

                    // Has this deferred been resolved?
                    isResolved: function() {
                        return !!( firing || fired );
                    },

                    // Cancel
                    cancel: function() {
                        cancelled = 1;
                        callbacks = [];
                        return this;
                    }
                };

            return deferred;
        },
        type: function( obj ) {
            return obj == null ?
                String( obj ) :
                class2type[ Object.prototype.toString.call(obj) ] || "object";
        }
    }
    // The DOM ready check for Internet Explorer
    function doScrollCheck() {
        if ( ReadyObj.isReady ) {
            return;
        }

        try {
            // If IE is used, use the trick by Diego Perini
            // http://javascript.nwbox.com/IEContentLoaded/
            document.documentElement.doScroll("left");
        } catch(e) {
            setTimeout( doScrollCheck, 1 );
            return;
        }

        // and execute any waiting functions
        ReadyObj.ready();
    }
    // Cleanup functions for the document ready method
    if ( document.addEventListener ) {
        DOMContentLoaded = function() {
            document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
            ReadyObj.ready();
        };

    } else if ( document.attachEvent ) {
        DOMContentLoaded = function() {
            // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", DOMContentLoaded );
                ReadyObj.ready();
            }
        };
    }
    function ready( fn ) {
        // Attach the listeners
        ReadyObj.bindReady();

        var type = ReadyObj.type( fn );

        // Add the callback
        readyList.done( fn );//readyList is result of _Deferred()
    }
    return ready;
})();

ready(function(){
	
	initFileUploads();
	uploadMap =  {}; 
	
	 if (navigator.appVersion.indexOf("MSIE") != -1)
		 isIE=true;
	
	var elements = getElementsByName_iefix('div','Uploaddiv');
	for(var i=0;i<elements.length;i++)
	{
		uploadMap[elements[i].id] = 1;
	}

	var e=document.getElementsByTagName("div");
	
});


